package controls;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import dao.Database;
import dto.TweetObj;
import model.Cube;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class GetTweets
 */
@WebServlet("/GetTweets")
public class GetTweets extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Connection conn = null;
    /**
     * Default constructor. 
     */
    public GetTweets() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		System.out.println("tesssssss");
		//System.out.println(request.getContentType());
		//System.out.println(request.getParameterMap());
//		String data  = "hell0";
//		if (request.getContentType().equals("application/json")) {
//	        data = "\"" + data + "\"";
//	    }
//	    response.getWriter().write(data);

       
		
		try{
			System.out.println("get test before");

			Database db = new Database();
		    conn = db.getConnection();
		//	System.out.println("befor cube");
		    Cube cube = new Cube();
			
			ArrayList<TweetObj> tList = cube.getTweets(conn, request, response);
			
			Gson gson = new Gson();
			String tweetsData = gson.toJson(tList);
			//response.getWriter().write("{\"tweets\":"+tweetsData+"}");
			 out.println("{\"tweets\":"+tweetsData+"}");
			// System.out.println("{\"tweets\":"+tweetsData+"}");
			
		}
		catch(Exception ex){
			out.println(ex.getMessage());
		}
		finally{
			out.close();
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
		
	}

}
